/**
 * 
 */
package bancosys.tec.security.impl.web.manager;

import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import bancosys.tec.persist.dao.BeanNotFoundException;
import bancosys.tec.security.impl.domain.User;
import bancosys.tec.security.impl.web.WebSecurityContext;

/**
 * @author gigante
 */
public class UserAwareHttpApplicationSecurityManager extends HttpApplicationSecurityManager {

    public static final String USER_IN_SESSION_KEY = HttpApplicationSecurityManager.class.getName() + ".USER";

    private static final Logger LOG = Logger.getLogger(UserAwareHttpApplicationSecurityManager.class);

    /**
     * @see bancosys.tec.security.impl.HttpApplicationSecurityManager#login(java.lang.String, java.lang.String)
     * @param username nome do usuário
     * @param password senha do usuário
     * @param context contexto de segurança
     * @return o subject do usuário
     */
    @Override
    public Subject login(String username, String password, WebSecurityContext context) {
        Subject ret = super.login(username, password, context);
        if (ret != null) {
            try {
                User user = super.getUserDao().findUser(username);
                context.getRequest().getSession().setAttribute(USER_IN_SESSION_KEY, user);
            } catch (BeanNotFoundException e) {
                LOG.debug("The user SHOULD exists.");
                throw new IllegalStateException("The user SHOULD exists.", e);
            }
        }
        return ret;
    }

    /**
     * @param request o request da sessão
     * @return o usuário na sessão
     */
    public User getUserInSession(HttpServletRequest request) {
        return (User) request.getSession().getAttribute(USER_IN_SESSION_KEY);
    }
}
